package com.bee.common.core.jsonview;

import java.util.ArrayList;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;

/**
 * Modified Spring 3.1's internal Return value handlers, and wires up a decorator
 * to add support for @JsonView
 * 
 * @author martypitt
 *
 */
public class JsonViewSupportFactoryBean implements InitializingBean {

   private	Logger log = LoggerFactory.getLogger(JsonViewSupportFactoryBean.class);
	
    @Autowired
    private RequestMappingHandlerAdapter adapter;
    
    @Override
    public void afterPropertiesSet() throws Exception {
    	List<HandlerMethodReturnValueHandler> handlers = adapter.getReturnValueHandlers();
        adapter.setReturnValueHandlers(decorateHandlers(handlers));
    }
    private List<HandlerMethodReturnValueHandler> decorateHandlers(List<HandlerMethodReturnValueHandler> handlers) {
    	 List<HandlerMethodReturnValueHandler> result = new ArrayList<HandlerMethodReturnValueHandler>();
    	for (HandlerMethodReturnValueHandler handler : handlers) {
            if (handler instanceof RequestResponseBodyMethodProcessor)
            {
            	result.add(new ViewInjectingReturnValueHandler(handler));
            }else{
            	result.add(handler);
            }
        } 
    	return result;
    }

}